var express = require('express');
var router = express.Router();
var mysql = require('./mysqlConfig');
var bodyParser = require("body-parser");
var config = require("../config.json");
var register = require('babel-core/register')
router.use(bodyParser.json({
    limit: "200000kb"
}));
router.use(bodyParser.urlencoded({
    parameterLimit: 100000,
    limit: '200000kb',
    extended: true
}));
const SMSClient = require('@alicloud/sms-sdk')
// ACCESS_KEY_ID/ACCESS_KEY_SECRET 根据实际申请的账号信息进行替换
const accessKeyId = config.duanxin.key;
const secretAccessKey = config.duanxin.secret;
/* GET home page. */
//处理连接数据库
const connectionMysql = (sql) => {
    return new Promise(function(resolve, reject) {
        mysql.getConnection(function(err, connection) {
            if (err) {
                reject(err)
                console.log(err)
            } else {
                resolve(sqlSever(connection, sql))
            }
        });
    });
}
//处理sql语句
const sqlSever = (connection, sql) => {
    return new Promise(function(resolve, reject) {
        connection.query(sql, function(err, rows, fields) {
            if (err) {
                console.log(err)
                reject(err);
            } else {
                console.log(err)
                resolve(rows);
                connection.release();
            }
        })
    });
}

//注册
router.post('/login', function(req, res, next) {
    var jobname = "'" + req.body.work + "'";
    var cName = "'" + req.body.cName + "'";
    var Name = "'" + req.body.Name + "'";
    var radio = "" + req.body.radio + "";
    var codeNum = "'" + req.body.codeNum + "'";
    var number = "'" + req.body.number + "'";
    var Email = "'" + req.body.Email + "'";
    var Password = "'" + req.body.Password + "'";
    var m_id = codeNum.substring(11, 17);

    //var sql = "INSERT INTO news (title,url) VALUES (" + title + "," + link_url + ")";
    var msql = "select id from m_member where mobile=" + number;
    connectionMysql(msql)
        .then((result) => {
            if (result.length == 0) {
                var sql = "INSERT INTO m_member (occupation,nickname,mem_name,gender,id_number,mobile,email,passWord,mem_id) VALUES (" + jobname + "," + cName + "," + Name + "," + radio + "," + codeNum + "," + number + "," + Email + "," + Password + "," + m_id + ")";
                console.log("****")
                console.log(sql)
                connectionMysql(sql)
                    .then((result) => {
                        var json = {
                            code: 200,
                            data: result
                        }
                        res.send(json);
                    })
                    .catch((reason) => {});

            } else {
                var json = {
                    code: 400,
                    data: "该手机号已经注册"
                }
                res.send(json);
            }

        })
        .catch((reason) => {});
});
//登录
router.get('/loading', function(req, res, next) {
    var number = "'" + req.query.number + "'";
    var Password = "'" + req.query.passWord + "'";
    var sql = "select id from m_member where mobile=" + number + "and passWord=" + Password;
    connectionMysql(sql)
        .then((result) => {
            console.log(result)
            if (result.length) {
                var json = {
                    code: 200,
                    data: result
                }
                res.send(json);
            } else {
                var json = {
                    code: 400,
                    data: "用户名或者密码错误"
                }
                res.send(json);
            }
        })
        .catch((reason) => {});
});
//修改
router.post('/updataMember', function(req, res, next) {

    var cName = "'" + req.body.cName + "'";
    var Name = "'" + req.body.Name + "'";
    var Gender = "" + req.body.gender + "";
    var jobname = "'" + req.body.work + "'";
    var codeNum = "'" + req.body.codeNum + "'";
    var number = "'" + req.body.number + "'";
    var Email = "'" + req.body.Email + "'";
    var Password = "'" + req.body.Password + "'";
    var Height = parseInt(req.body.height);
    var Weight = parseInt(req.body.weight);
    var Merry = "'" + req.body.merry + "'";
    var Children = "'" + req.body.children + "'";
    var Interest = "'" + req.body.interest + "'";
    var Household = "'" + req.body.household + "'";
    var Housestate = "'" + req.body.housestate + "'";
    var BodyStatus = "'" + req.body.bodyStatus + "'";
    var Spouse = "'" + req.body.spouse + "'";
    var MobileVC = "'" + req.body.mobileVC + "'";
    var mem_id = codeNum.substring(11, 17);
    var mem_img = "'" + req.body.mem_img + "'";
    var id_cardImgz = "'" + req.body.id_cardImgz + "'";
    var id_cardImgf = "'" + req.body.id_cardImgf + "'";
    var id_cardImga = "'" + req.body.id_cardImga + "'";

    var sql = "update m_member set id_cardImga=" + id_cardImga + " , id_cardImgf=" + id_cardImgf + " ,id_cardImgz=" + id_cardImgz + " , mem_img=" + mem_img + " ,nickname=" + cName + " , gender=" + Gender + " , occupation=" + jobname + " , id_number=" + codeNum + " , mobile=" + number + " , email=" + Email + " , mem_id=" + Password + " , height=" + Height + " , body_weight=" + Weight + " , marital_status=" + Merry + " , has_children=" + Children + " , character_love=" + Interest + " , account_location=" + Household + " , housing_status=" + Housestate + " , body_condition=" + BodyStatus + " , love_object=" + Spouse + " , bar_code=" + MobileVC + " , mem_name=" + Name + "where mobile=" + number;
    console.log(sql, 23)
    connectionMysql(sql)
        .then((result) => {
            console.log(result, 2)
            var json = {
                code: 200,
                data: result
            }
            console.log("*****")
            res.send(json);
        })
        .catch((reason) => {
            console.log(reason, 1)
        });
});



//获取所有用户列表
router.get('/getAllMember', function(req, res, next) {

    var sql = 'select * from m_member where yn = 1';
    connectionMysql(sql)
        .then((result) => {
            var json = {
                code: 200,
                data: result
            }
            res.send(json);
        })
        .catch((reason) => {});
});

//根据id获取用户信息
router.get('/getMemberinfo', function(req, res, next) {
    var id = "'" + req.query.id + "'";
    var sql = 'select * from m_member where id=' + id;

    connectionMysql(sql)
        .then((result) => {
            var json = {
                code: 200,
                data: result
            }
            res.send(json);
        })
        .catch((reason) => {});
});
//根据电话获取用户信息
router.get('/getMemberinfoByNum', function(req, res, next) {
    var number = "'" + req.query.number + "'";
    var sql = 'select * from m_member where mobile=' + number;

    connectionMysql(sql)
        .then((result) => {
            var json = {
                code: 200,
                data: result
            }
            res.send(json);
        })
        .catch((reason) => {});
});
//上传图片
router.post('/uploadImage', function(req, res, next) {
    console.log("****");
    console.log(req.body.image_base64);
    var fs = require('fs');　　　　
    var path = './public/images/' + Date.now() + '.png'; //从app.js级开始找--在我的项目工程里是这样的
    var base64 = req.body.image_base64;
    var dataBuffer = new Buffer(base64, 'base64'); //把base64码转成buffer对象，
    fs.writeFile(path, dataBuffer, function(err) { //用fs写入文件
        if (err) {
            var json = {
                "code": 400,
                "msg": "图片过大"
            }
            res.send(json);
        } else {
            var json = {
                code: 200,
                "url": path
            }
            res.send(json);
        }
    });
});

//根据电话获取用户信息
router.get('/getMemberinfoByNum', function(req, res, next) {
    var number = "'" + req.query.number + "'";
    var sql = 'select * from m_member where mobile=' + number;

    connectionMysql(sql)
        .then((result) => {
            var json = {
                code: 200,
                data: result
            }
            res.send(json);
        })
        .catch((reason) => {});
});

//获取会员点赞

router.get('/getMyComments', function(req, res, next) {
    var number = "'" + req.query.number + "'";
    var sql = 'select * from m_member where mobile=' + number;

    connectionMysql(sql)
        .then((result) => {
            var json = {
                code: 200,
                data: result
            }
            res.send(json);
        })
        .catch((reason) => {});
});

//获取会员关注
router.get('/getMyCollection', function(req, res, next) {
    var number = "'" + req.query.number + "'";
    var sql = 'select * from m_member where mobile=' + number;

    connectionMysql(sql)
        .then((result) => {
            var json = {
                code: 200,
                data: result
            }
            res.send(json);
        })
        .catch((reason) => {});
});

//获取会员活动
// var sql = 'select ac.* ,m.nickname ,m.mem_img from activity_comment ac left join m_member m on m.mobile = ac.mem_id where acti_no=' + acti_no;
router.get('/getMyActivity', function(req, res, next) {
    var number = "'" + req.query.number + "'";
    var sql = 'select c.* ,a.title,a.acti_no from event_registration c left join activities a on a.acti_no =c.acti_no  where mem_id=' + number;
    connectionMysql(sql)
        .then((result) => {
            var json = {
                code: 200,
                data: result
            }
            res.send(json);
        })
        .catch((reason) => {});
});
//获取验证码
router.get('/getPhoneCode', function(req, res, next) {
    var mobile = "" + req.query.mobile + "";
    //初始化sms_client
    let smsClient = new SMSClient({
        accessKeyId,
        secretAccessKey
    })
    var num = randomNum(1000, 9999);
    var code = '{"code":' + num + '}'
    console.log(code)
    var sql = 'select phone from SMS_LOG where phone=' + mobile;
    connectionMysql(sql)
        .then((result) => {
            console.log("****")
            console.log(result.length)
            var ssql = "";

            if (result.length == 0) {
                ssql = "insert into SMS_LOG (sms_id,phone,ver_code) values ('" + mobile + "','" + mobile + "','" + num + "')";


            } else {
                ssql = "update  SMS_LOG  set ver_code='" + num + "' where phone='" + mobile + "'";
            }
            console.log(ssql)
            connectionMysql(ssql)
                .then((result) => {
                    var json = {
                        code: 200,
                        data: result
                    }
                    res.send(json);
                })
                .catch((reason) => {

                });

        })
        .catch((reason) => {});
    //发送短信

    smsClient.sendSMS({
        PhoneNumbers: mobile,
        SignName: config.duanxin.SignName,
        TemplateCode: config.duanxin.TemplateCode,
        TemplateParam: '{"code":"' + num + '"}'
    }).then(function(res) {
        let {
            Code
        } = res
        if (Code === 'OK') {
            //处理返回参数
            console.log("*****1")
            console.log(res)

        } else {
            console.log("*****2")
            console.log(res)
        }
    }, function(err) {
        console.log("*****3")
        console.log(err)
    })
});



function randomNum(minNum, maxNum) {
    switch (arguments.length) {
        case 1:
            return parseInt(Math.random() * minNum + 1, 10);
            break;
        case 2:
            return parseInt(Math.random() * (maxNum - minNum + 1) + minNum, 10);
            break;
        default:
            return 0;
            break;
    }
}
module.exports = router;